<template>
	<div class="visitLog-container">
		<el-dialog v-model="isShowDialog" :title="props.title" :width="800" draggable="" append-to-body="true">
			<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="訪客類型" prop="type">
							<el-select  clearable v-model="ruleForm.type" placeholder="请选择訪客類型">
								<el-option v-for="(item,index) in getEnumSelectorList('VisitorType')" :key="index" :label="item.name" :value="item.code">{{ item.name }}</el-option>
								
							</el-select>
							
						</el-form-item>
						
					</el-col>
					<el-form-item v-show="false">
						<el-input v-model="ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="訪客手機" prop="vphone">
							<el-input v-model="ruleForm.vphone" placeholder="请输入訪客手機" maxlength="50" show-word-limit clearable />
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="訪客姓名" prop="visitor">
							<el-input v-model="ruleForm.visitor" placeholder="请输入訪客姓名" maxlength="50" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="訪客性別" prop="sex">
							<el-select  clearable v-model="ruleForm.sex" placeholder="请选择訪客性別">
								<el-option v-for="(item,index) in getEnumSelectorList('SexType')" :key="index" :label="item.name" :value="item.code">{{ item.name }}</el-option>
								
							</el-select>
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="訪客身份證" prop="idCard">
							<el-input v-model="ruleForm.idCard" placeholder="请输入訪客身份證" maxlength="50" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="車牌號" prop="carNo">
							<el-input v-model="ruleForm.carNo" placeholder="请输入車牌號" maxlength="50" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="預約來訪時間" prop="visitTime">
							<el-date-picker v-model="ruleForm.visitTime" type="datetime" placeholder="預約來訪時間"  />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="預約結束時間" prop="vendTime">
							<el-date-picker v-model="ruleForm.vendTime" type="datetime" placeholder="預約結束時間"  />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="出入門禁點" prop="visitSite">
							<el-input v-model="ruleForm.visitSite" placeholder="请输入出入門禁點" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="來訪單位" prop="vcompany">
							<el-input v-model="ruleForm.vcompany" placeholder="请输入來訪單位" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="訪客人數" prop="vnum">
							<el-input v-model="ruleForm.vnum" placeholder="请输入訪客人數" maxlength="18" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="拜訪事由" prop="vreason">
							<el-input v-model="ruleForm.vreason" placeholder="请输入拜訪事由" maxlength="1000" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="人臉頭像" prop="vimg">
							<el-upload
							list-type="picture-card"
							:limit="1"
							:show-file-list="false"
							ref="uploadVimgRef"
							:on-exceed="handleExceedVimg"
							:before-upload="handleBeforeUploadVimg"
							:auto-upload="true"
							:http-request="uploadVimgHandle">
								<img
								v-if="ruleForm.vimg"
								:src="ruleForm.vimg"
								style="width: 100%; height: 100%; object-fit: contain"/>
								<el-icon v-else><Plus /></el-icon>
								
							</el-upload>
							
						</el-form-item>
						
					</el-col>
				
					<el-col :xs="24" :span="8" class="mb20">
						<el-form-item label="證件照片" prop="docImg">
							<el-upload class="upload-more" drag v-model:file-list="docImgArrs" :auto-upload="true" multiple :limit="3" ref="uploadDocImgRef"
								:http-request="uploadDocImgHandle" :before-upload="handleBeforeUploadDocImg" :on-remove="handleRemoveDocImg"
								:on-exceed="handleExceedDocImg">
								<el-icon class="el-icon--upload"><upload-filled /></el-icon>
								<div class="el-upload__text">
									<em>拖拽或点击上传</em>
								</div>
								<template #tip>
									<div class="el-upload__tip">
										单个文件的大小不能超过3MB
									</div>
								</template>
							</el-upload>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :span="8" class="mb20">
						<el-form-item label="物品信息" prop="goodsInfo">
							<el-upload class="upload-more" drag v-model:file-list="goodsInfoArrs" :auto-upload="true" multiple :limit="3" ref="uploadGoodsInfoRef"
								:http-request="uploadGoodsInfoHandle" :before-upload="handleBeforeUploadGoodsInfo" :on-remove="handleRemoveGoodsInfo"
								:on-exceed="handleExceedGoodsInfo">
								<el-icon class="el-icon--upload"><upload-filled /></el-icon>
								<div class="el-upload__text">
									<em>拖拽或点击上传</em>
								</div>
								<template #tip>
									<div class="el-upload__tip">
										单个文件的大小不能超过3MB
									</div>
								</template>
							</el-upload>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="作業區域" prop="visitArea">
							<el-input v-model="ruleForm.visitArea" placeholder="请输入作業區域" maxlength="100" show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="部門" prop="deptId">
							<el-select clearable filterable v-model="ruleForm.deptId" placeholder="被訪部門" @change="DeptIdChange">
								<el-option v-for="(item,index) in sysOrgDeptIdDropdownList" :key="index" :value="item.value" :label="item.label" />
								
							</el-select>
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="被訪負責人" prop="leaderId">
							<el-select clearable filterable v-model="ruleForm.leaderId" placeholder="请选择被訪負責人" @change="LeaderIdChange">
								<el-option v-for="(item,index) in sysUserLeaderIdDropdownList" :key="index" :value="item.value" :label="item.label" />
								
							</el-select>
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="被訪人姓名" prop="staff">
							<el-input v-model="ruleForm.staff" placeholder="请输入被訪人姓名" maxlength="50" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="被訪人手機" prop="iphone">
							<el-input v-model="ruleForm.iphone" placeholder="请输入被訪人手機" maxlength="50" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="狀態" prop="status">
							<el-select  clearable v-model="ruleForm.status" placeholder="请选择狀態">
								<el-option v-for="(item,index) in getEnumSelectorList('ProcessStatus')" :key="index" :label="item.name" :value="item.code">{{ item.name }}</el-option>
								
							</el-select>
							
						</el-form-item>
						
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
	import { ref,onMounted,nextTick } from "vue";
	import { ElMessage } from "element-plus";
	import type { FormRules } from "element-plus";
	import _ from 'lodash';
	import { getEnumSelectorList } from "/@/utils/enumHelper";
	import { genFileId } from 'element-plus';
	import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
    import { Plus,UploadFilled } from "@element-plus/icons-vue";
    import { UploadRequestOptions } from "element-plus";
    import {uploadVimg,uploadDocImg,uploadGoodsInfo} from '/@/api/main/visitLog';
	import { addVisitLog, updateVisitLog } from "/@/api/main/visitLog";
	import { getSysOrgDeptIdDropdown } from '/@/api/main/visitLog';
	import { getSysUserLeaderIdDropdown } from '/@/api/main/visitLog';

	
	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["reloadTable"]);
	const ruleFormRef = ref();
	   const uploadVimgRef = ref();
	   const vimgArrs=ref([]);
	   const uploadDocImgRef = ref();
	   const docImgArrs=ref([]);
	   const uploadGoodsInfoRef = ref();
	   const goodsInfoArrs=ref([]);
	const isShowDialog = ref(false);
	const ruleForm = ref<any>({});
	const timer=ref<any>();
	let mianPageData=ref<any>();
	//自行添加其他规则
	const rules = ref<FormRules>({
		visitor: [{required: true, message: '请输入訪客姓名！', trigger: 'blur',},],
		vphone: [{required: true, message: '请输入手机号！', trigger: 'blur',},],
		type: [{required: true, message: '请输入訪客类型！', trigger: 'blur',},],
		idCard: [{required: true, message: '请输入訪客类型！', trigger: 'blur',},],
		visitTime: [{required: true, message: '请选择预约来访时间！', trigger: 'blur',},],
		vendTime: [{required: true, message: '请选择预约结束时间！', trigger: 'blur',},],
		sex: [{required: true, message: '请选择性别！', trigger: 'blur',},],
		vimg: [{required: true, message: '请选择人脸照片！', trigger: 'blur',},],
		// deptId: [{required: true, message: '请选择被访问部门！', trigger: 'blur',},],
		// leaderId: [{required: true, message: '请选择被访責任人！', trigger: 'blur',},],
	});

	// 打开弹窗
	const openDialog = (row: any,notParentCall=false) => {
	    mianPageData.value = row
	    timer.value = new Date().getTime();
		ruleForm.value.$TemplateFieldDisabled = notParentCall;
		if(row!=null && notParentCall ==false){
		  ruleForm.value = JSON.parse(JSON.stringify(row));
		  }
		else {
			//作為新增明細時候的組件使用
			if(row.id!=undefined &&notParentCall==true){
			  ruleForm.value.$TemplateField =row.id;
			}
		}
		isShowDialog.value = true;
		   docImgArrs.value =[];
		   
		if(ruleForm.value.docImg!=null&&ruleForm.value.docImg!=undefined)
		{
					  var arrDocImgs=  JSON.parse(ruleForm.value.docImg);
					  arrDocImgs.forEach(r=>{
						  if(r.name==undefined){
							 var splits= r.split('/');
							   docImgArrs.value.push({
								   name:splits[splits.length-1],
								   url:r
							   });
						  }else{
							   docImgArrs.value.push(r);
						  }
					  });
		}
		 
		   goodsInfoArrs.value =[];
		   if( ruleForm.value.goodsInfo!=null&&ruleForm.value.goodsInfo!=undefined)
		   {
		   			  var arrGoodImgs=  JSON.parse(ruleForm.value.goodsInfo);
		   			  arrGoodImgs.forEach(r=>{
		   				  if(r.name==undefined){
		   					 var splits= r.split('/');
		   					   goodsInfoArrs.value.push({
		   						   name:splits[splits.length-1],
		   						   url:r
		   					   });
		   				  }else{
		   					   goodsInfoArrs.value.push(r);
		   				  }
		   			  });
		   }
		   
		   
	
			getDeptIdDropdownList();
			getLeaderIdDropdownList();
		//新增的时候需要给集合字段赋值为： []
		if(row.id==undefined){
		}
	};

	// 关闭弹窗
	const closeDialog = () => {
		emit("reloadTable");
		isShowDialog.value = false;
	};

	// 取消
	const cancel = () => {
		isShowDialog.value = false;
	};

	// 提交
	const submit = _.throttle( async () => {
		ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
			if (isValid) {
				let values = ruleForm.value;
				if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
					await addVisitLog(values);
				} else {
					await updateVisitLog(values);
				}
				closeDialog();
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	},2000);


	const DeptIdChange = async (changeItem) => {
		var item= sysOrgDeptIdDropdownList.value.find(r=>r.value == changeItem);
		if(item!=null){
		}
	  }
	const sysOrgDeptIdDropdownList = ref<any>([]); 
	const getDeptIdDropdownList = async () => {
	    var model=ruleForm.value;
	    let list = await getSysOrgDeptIdDropdown(model);
		sysOrgDeptIdDropdownList.value = list.data.result ?? [];
	};
	
	const LeaderIdChange = async (changeItem) => {
		var item= sysUserLeaderIdDropdownList.value.find(r=>r.value == changeItem);
		if(item!=null){
		}
	  }
	const sysUserLeaderIdDropdownList = ref<any>([]); 
	const getLeaderIdDropdownList = async () => {
	    var model=ruleForm.value;
	    let list = await getSysUserLeaderIdDropdown(model);
		sysUserLeaderIdDropdownList.value = list.data.result ?? [];
	};
	




	const uploadVimgHandle = async (options: UploadRequestOptions) => {
		const res = await uploadVimg(options);
		ruleForm.value.vimg = res.data.result?.url;
	};
	const handleExceedVimg: UploadProps['onExceed'] = (files) => {
		nextTick(() => {
	 		 uploadVimgRef.value!.clearFiles();
	   		const file = files[0];
	   		file.uid = genFileId();
	   		uploadVimgRef.value!.handleStart(file);
	 		uploadVimgRef.value!.submit();
	   	});	
	};
	 const handleBeforeUploadVimg = (file) => {
			 const maxSize = 6 * 1024 * 1024;  // 设置文件大小限制为3MB
			 if (file.size > maxSize) {
				 ElMessage({
					 message: `${file.name}-文件大小超过了${maxSize / (1024 * 1024)}MB的限制`,
					 type: "error",
				 });
				 return false;  // 阻止文件上传
			 }
			 return true;  // 允许文件上传
		 }
	    const uploadDocImgHandle = async (options: UploadRequestOptions) => {
		const res = await uploadDocImg(options);
		docImgArrs.value.forEach(r=>{
			if(r.uid == options.file.uid)
			  r.url= res.data.result?.url;
		});
		ruleForm.value.docImg =JSON.stringify(docImgArrs.value.map(r=>({
			name:r.name,
			url:r.url
		})));
		};
		const handleRemoveDocImg: UploadProps['onRemove'] = (removeFile, uploadFiles) => {
			docImgArrs.value =docImgArrs.value.filter(r=>r.name!=removeFile.name);
		    ruleForm.value.docImg =JSON.stringify(docImgArrs.value.map(r=>({
		    	name:r.name,
		    	url:r.url
		    })));
		};
		const handleExceedDocImg: UploadProps['onExceed'] = (files) => {
		nextTick(() => {
	 		 uploadDocImgRef.value!.clearFiles();
			files.forEach(file => {
				file.uid = genFileId();
				uploadDocImgRef.value!.handleStart(file);
			});
			uploadDocImgRef.value!.submit();
	   	});	
		};
			 const handleBeforeUploadDocImg = (file) => {
			 const maxSize = 10 * 1024 * 1024;  // 设置文件大小限制为3MB
			 if (file.size > maxSize) {
				 ElMessage({
					 message: `${file.name}-文件大小超过了${maxSize / (1024 * 1024)}MB的限制`,
					 type: "error",
				 });
				 return false;  // 阻止文件上传
			 }
			 return true;  // 允许文件上传
		 }

		const uploadGoodsInfoHandle = async (options: UploadRequestOptions) => {
		const res = await uploadGoodsInfo(options);
		goodsInfoArrs.value.forEach(r=>{
			if(r.uid == options.file.uid)
			  r.url= res.data.result?.url;
		});
		ruleForm.value.goodsInfo =JSON.stringify(goodsInfoArrs.value.map(r=>({
			name:r.name,
			url:r.url
		})));
		};
		const handleRemoveGoodsInfo: UploadProps['onRemove'] = (removeFile, uploadFiles) => {
			goodsInfoArrs.value =goodsInfoArrs.value.filter(r=>r.name!=removeFile.name);
		    ruleForm.value.goodsInfo =JSON.stringify(goodsInfoArrs.value.map(r=>({
		    	name:r.name,
		    	url:r.url
		    })));
		};
		const handleExceedGoodsInfo: UploadProps['onExceed'] = (files) => {
		nextTick(() => {
	 		 uploadGoodsInfoRef.value!.clearFiles();
			files.forEach(file => {
				file.uid = genFileId();
				uploadGoodsInfoRef.value!.handleStart(file);
			});
			uploadGoodsInfoRef.value!.submit();
	   	});	
		};
			 const handleBeforeUploadGoodsInfo = (file) => {
			 const maxSize = 10 * 1024 * 1024;  // 设置文件大小限制为3MB
			 if (file.size > maxSize) {
				 ElMessage({
					 message: `${file.name}-文件大小超过了${maxSize / (1024 * 1024)}MB的限制`,
					 type: "error",
				 });
				 return false;  // 阻止文件上传
			 }
			 return true;  // 允许文件上传
		 }

	const checkNeedDisable =(previousColumn)=>{
	     if(typeof previousColumn !== 'undefined' && previousColumn != null && previousColumn !== ''&&previousColumn>0){
		   return false;
			}
	   return true;
	}

	// 页面加载时
	onMounted(async () => {
	});

	const commentClick =async (row : any) => {
		timer.value = new Date().getTime();
		//ruleForm.value.standardId = row.id;
		isShowDialog.value = true;
	};

	//将属性或者函数暴露给父组件
	defineExpose({ openDialog,commentClick });
</script>




